using System.Collections.Generic;
using Godot.Collections;

public class InGame
{
    public Array messages = new Array();
    public long roomid;
    public int roundChessman = 0;
    public Player playerA;
    public Player playerB;

    public int[,] guid = new int[3, 3];
    public InGame Parse(Dictionary dict)
    {
        Array array = (Array)dict["guid"];
        for (int x = 0; x < 3; x++)
            for (int y = 0; y < 3; y++)
            {
                guid[x, y] = (int)array[x * 3 + y];
            }
        roundChessman = (int)dict["roundstate"];
        Dictionary A = (Dictionary)dict["playerA"];
        Dictionary B = (Dictionary)dict["playerB"];
        messages = (Array)dict["messages"];
        playerA = new Player().Parse(A);
        playerB = new Player().Parse(B);
        return this;
    }
    public Dictionary ToDictionary()
    {
        Array aguid = new Array();
        for (int x = 0; x < 3; x++)
            for (int y = 0; y < 3; y++)
            {
                aguid.Add(guid[x, y]);
            }
        return new Dictionary()
        {
            {"guid",aguid},
            {"messages",messages},
            {"roundstate",roundChessman},
            {"playerA",playerA.ToDictionary()},
            {"playerB",playerB.ToDictionary()}
        };
    }
    public bool Chekdeuce()
    {
        for (int x = 0; x < 3; x++)
        {
            for (int y = 0; y < 3; y++)
            {
                if (guid[x, y] == 0)
                {
                    return false;
                }
            }
        }
        return true;
    }
    public (bool, int) ChekWin()
    {
        int[,] map = new int[3, 3];
        for (int x = 0; x < 3; x++)
        {
            for (int y = 0; y < 3; y++)
            {
                map[x, y] = guid[x, y];
                if (guid[x, y] == 2) map[x, y] = -1;
            }
        }

        for (int x = 0; x < 3; x++)
        {
            int c = 0;
            for (int y = 0; y < 3; y++)
            {
                c += map[x, y];
            }
            if (c == 3) return (true, 1);
            if (c == -3) return (true, 2);
        }
        for (int y = 0; y < 3; y++)
        {
            int c = 0;
            for (int x = 0; x < 3; x++)
            {
                c += map[x, y];
            }
            if (c == 3) return (true, 1);
            if (c == -3) return (true, 2);
        }
        int c1 = 0;
        for (int i = 0; i < 3; i++)
            c1 += map[i, i];
        if (c1 == 3) return (true, 1);
        if (c1 == -3) return (true, 2);
        int c2 = 0;
        for (int i = 2; i >= 0; i--)
            c2 += map[i, 2 - i];
        if (c2 == 3) return (true, 1);
        if (c2 == -3) return (true, 2);
        return (false, 0);
    }
    public Player GetPlayer(int c)
    {
        if (playerA.chessman == c) return playerA;
        else return playerB;
    }
}